package com.weishui.downloading.download;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import com.weishui.downloading.app.DownLaodWindow;


public class DownLoadThread implements Runnable {

	private URL url;
	private int downLoadLength;
	private int offset;
	private String downLoadFileName;
	private Proxy proxy;
	public DownLoadThread(URL url,int downLoadLength,int offset,String downLoadFileName,Proxy proxy){
		this.url = url;
		this.downLoadLength = downLoadLength;
		this.offset = offset;
		this.downLoadFileName = downLoadFileName;
		this.proxy = proxy;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		DwnLoadOperator.DOWNLAOD_COUNT ++;
		try {
			URLConnection urlConnection;
			File downLoadFile = new File(downLoadFileName);
			if(proxy == null){
				urlConnection = url.openConnection();
			}else{
				urlConnection = url.openConnection(proxy);
			}
			urlConnection.setRequestProperty("RANGE","bytes=" + offset + "-");
			InputStream inputStream = urlConnection.getInputStream();
			OutputStream outputStream = new FileOutputStream(downLoadFile,false);
			byte[] readData = new byte[1024*10];
			int readSize;
			int readLength = 0;
			DownLaodWindow.addLog("线程 "+ Thread.currentThread().getId() + "开始下载");
			while((readSize = inputStream.read(readData)) != -1){
				readLength += readSize;
				if(readLength > downLoadLength){
					readSize = readSize - (readLength - downLoadLength);
				}
				outputStream.write(readData, 0, readSize);
				if(readLength > downLoadLength){
					break;
				}
			}
			inputStream.close();
			outputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DwnLoadOperator.DOWNLAOD_COUNT --;
		DownLaodWindow.addLog("线程 "+ Thread.currentThread().getId() + "下载完成");
	}

}
